const communityservice = require("../../../apiservice/community/communityservice");
var currentIndex = -1;
let userInfo = getApp().globalData.userInfo;
var area = require("../../../utils/area.js")
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		editShow: false,
		region: ['湖南省', '长沙市', '芙蓉区'],
		communitylist: [],
		userinfo: [],
		community: {},
		currentname: '',
		currentcontact: '',
		currentmobile: '',
		street: [{
			new_name: '全部',
			new_streetid: null
		}],
		streetIndex: 0,
		streetid: null,
		opentype: "detail",
		userid: '',
    showDistrict:false,
    // areaList:[]
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		
		//加载默认地区社区信息
		//this.getCommunityByPCA(this.data.region[0], this.data.region[1], this.data.region[2]);
		//加载街道
    if(options.communityId)
    {
      var that = this;
      communityservice.getCommunityById(options.communityId).then(function (success) {
        console.log("社区" + success.data);
        var region = [];
        region.push(success.data.new_provinceName);
        region.push(success.data.new_cityName);
        region.push(success.data.new_countyName);
        that.setData({
          region: region
        });
        const eventChannel = that.getOpenerEventChannel();
        eventChannel.on('openedCommunityPage', function (e) {
          that.setData({
            opentype: e.data
          })
        })
        that.GetStreetByPCA(that.data.region[0], that.data.region[1], that.data.region[2]);
        
      }).catch(function (ex) {
        console.log(ex);
      })

    }
    else{
      userInfo = getApp().globalData.userInfo;
      if (userInfo != null) {

        this.setData({
          userid: userInfo.userid
        });
        var region = [];
        region.push(userInfo.new_provincename);
        region.push(userInfo.new_cityname);
        if (userInfo.new_areaname) {
          region.push(userInfo.new_areaname);
        } else {
          region.push('');
        }
        this.setData({
          region: region
        })
      }
      
      var that = this;
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on('openedCommunityPage', function (e) {
        that.setData({
          opentype: e.data
        })
      })
      this.GetStreetByPCA(this.data.region[0], this.data.region[1], this.data.region[2]);
      this.setData({
        userinfo: userInfo
      });
      
    }
	},
  districtTap:function(e){
    this.setData({ showDistrict: true});    
  },

  areaConfirm:function(e){
    console.log(e.detail);
    this.setData({ showDistrict: false });
    var provinceName = e.detail.currentTarget.dataset.province;
    var cityName = e.detail.currentTarget.dataset.city;
    var areaName = e.detail.currentTarget.dataset.area;
    //if(e.detail.values.length>0){
    var region = [];
    region.push(provinceName);
    region.push(cityName);
    region.push(areaName);
    this.setData({
      region: region,
      street: [{
        new_name: '全部',
        new_streetid: null
      }],
      streetIndex: 0
    });
      wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
        title: '加载中',
        icon: 'loading'
      });
      //console.log('picker发送选择改变，携带值为', e.detail.value);
      if (provinceName == "全部") {
        wx.showToast({
          title: "省区不能为全部",
          icon: "none",
          mask: true,
          duration: 2500
        })
        return;
      }
      this.getCommunityByPCA(provinceName, cityName, areaName);
      this.GetStreetByPCA(this.data.region[0], this.data.region[1], this.data.region[2]);
      wx.hideLoading();
    //}
  },

	editItem: function(e) {
		this.setData({
			editShow: true,
			currentcontact: '',
			currentmobile: '',
			currentname: ''
		})
		this.getCommunityById(e.currentTarget.dataset.id);

	},
	//监听修改事件
	onChange: function(e) {
		var target = e.currentTarget.dataset.id;
		if (target == 'contactname') {
			this.setData({
				['community.new_contactName']: e.detail
			})
		}
		if (target == 'mobile') {
			this.setData({
				['community.new_mobile']: e.detail
			})
		}
		if (target == 'name') {
			this.setData({
				['community.new_name']: e.detail
			})
		}
	},
	// 修改街道信息
	onSure: function(e) {
		wx.showLoading({
			title: '提交中',
			mask: true,
		})
		var currentId = this.data.community.new_communityId;
		var name = this.data.community.new_name;
		var mobile = this.data.community.new_mobile;
		var contactname = this.data.community.new_contactName;
		var communityobj = {
			new_communityId: currentId,
			new_name: name,
			new_mobile: mobile,
			contactName: contactname,
			new_contact: this.data.community.new_contact,
			userid: this.data.userinfo.userid
		};
		console.log(communityobj);
		this.modCommunityById(communityobj);
	},

	onClose: function() {
		this.setData({
			editShow: false
		})
	},
	// 跳转至详细页面
	enterDetail: function(e) {
		if (this.data.opentype == "choose") {
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.emit('communityEvent', {
				communityName: e.currentTarget.dataset.name,
				communityId: e.currentTarget.id
			});
			wx.navigateBack({
				delta: 1
			})
		} else {
			//console.log(e);
			wx.navigateTo({
				url: '/pages/community/detail/detail?id=' + e.currentTarget.id
			})
		}


	},
	// 添加社区
	addCommunity: function() {

		let provinceid = userInfo.new_provincename;
		let cityid = userInfo.new_cityname;
		let countyid = userInfo.new_areaname;
        //debugger;
		if (this.data.communitylist 
		&& this.data.communitylist.length > 0
		&& this.data.communitylist[0].new_provinceName
		&& this.data.communitylist[0].new_cityName
		&& this.data.communitylist[0].new_countyName) {
			provinceid = this.data.communitylist[0].new_provinceName;
			cityid = this.data.communitylist[0].new_cityName;
			countyid = this.data.communitylist[0].new_countyName;
		}
		wx.navigateTo({
			url: '/pages/community/add/add?provinceid=' + provinceid + '&cityid=' + cityid + '&countyid=' + countyid
		})

	},
	// 搜索社区
	onSearch: function(e) {
		//console.log("用户搜索" + e.detail.searchKey);

		if (e.detail.searchKey.replace(/\s+/g, '') == '') {
			wx.showToast({
				title: '请输入社区名称',
				icon: 'none',
				duration: 2000
			});
		} else {
			var community = {
				new_provinceName: this.data.region[0],
				new_cityName: this.data.region[1],
				new_countyName: this.data.region[2],
				new_name: e.detail.searchKey,
				new_street: this.data.schoolid
			}
			wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
				title: '加载中',
				icon: 'loading'
			});
			this.getCommunityByName(community);
			wx.hideLoading();
		}
	},
	bindStreetChange: function(e) {
		// debugger
		//console.log(this.data.schoolList[e.detail.value]);
		wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
			title: '加载中',
			icon: 'loading'
		});
		console.log(e.detail.value);
		this.setData({
			streetIndex: e.detail.value,
			schoolid: this.data.street[e.detail.value].new_streetId
		});
		console.log(this.data.street);
		if (e.detail.value == "0") {
			var community = {
				new_provinceName: this.data.region[0],
				new_cityName: this.data.region[1],
				new_countyName: this.data.region[2]
			}
			this.getCommunityByName(community);
		} else {
			var community = {
				new_provinceName: this.data.region[0],
				new_cityName: this.data.region[1],
				new_countyName: this.data.region[2],
				new_street: this.data.schoolid
			}
			this.getCommunityByName(community);
		}
		wx.hideLoading();
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		// if (this.data.streetIndex == "0") {
		// 	var community = {
		// 		new_provinceName: this.data.region[0],
		// 		new_cityName: this.data.region[1],
		// 		new_countyName: this.data.region[2]
		// 	}
		// 	this.getCommunityByName(community);
		// } else {
		// 	var community = {
		// 		new_provinceName: this.data.region[0],
		// 		new_cityName: this.data.region[1],
		// 		new_countyName: this.data.region[2],
		// 		new_street: this.data.schoolid
		// 	}
		// 	this.getCommunityByName(community);
		// }
	},


	// 根据省市区加载社区
	getCommunityByPCA: function(province, city, area) {
		var that = this;
		communityservice.getCommunityByPAC(province, city, area).then(function(success) {
			console.log(success);
			that.setData({
				communitylist: success.data
			});
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	// 根据社区名称获取社区getCommunityByName
	getCommunityByName: function(obj) {
		var that = this;
		communityservice.getCommunityByName(obj).then(function(success) {
			console.log(success);
			that.setData({
				communitylist: success.data
			});
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	// 根据社区ID获取社区
	getCommunityById: function(id) {
		var that = this;
		communityservice.getCommunityById(id).then(function(success) {
			console.log("社区", success.data);
			that.setData({
				community: success.data
			});
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	// 修改社区信息
	modCommunityById: function(obj) {
		var that = this;
		communityservice.modCommunityById(obj).then(function(success) {
			that.showResult(success.data);
			that.setData({
				editShow: false
			});
			
		   that.onShow();
		}).catch(function(ex) {
			that.setData({
				editShow: false
			});
			console.log(ex);
		})

	},
	// 获取街道
	GetStreetByPCA: function(provinceName, cityName, areaName) {
		var that = this;
		communityservice.GetStreetByPCA(provinceName, cityName, areaName).then(function(success) {
			that.setData({
				street: that.data.street.concat(success.data)
			});
      that.getCommunityByPCA( provinceName,  cityName, areaName)
		}).catch(function(ex) {
			console.log(ex);
		})

	},
	// 位置监听事件
	bindRegionChange: function(e) {
		console.log(e);
		wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
			title: '加载中',
			icon: 'loading'
		});
		//console.log('picker发送选择改变，携带值为', e.detail.value);
		if (e.detail.value[0] == "全部") {
			wx.showToast({
				title: "省区不能为全部",
				icon: "none",
				mask: true,
				duration: 2500
			})
			return;
		}
		this.getCommunityByPCA(e.detail.value[0], e.detail.value[1], e.detail.value[2]);
		this.setData({
			region: e.detail.value,
			street: [{
				new_name: '全部',
				new_streetid: null
			}],
			streetIndex: 0
		});
		this.GetStreetByPCA(this.data.region[0], this.data.region[1], this.data.region[2]);
		wx.hideLoading();
	},
	showResult: function(res) {
		var title = '';
		var icon = '';
		if (res.resultState == 1) {
			title = '修改成功';
			icon = 'success';
		} else {
			title = '修改失败';
			icon = 'none';
		}
		wx.showToast({
			title: title,
			icon: icon,
			duration: 2000
		});
	},
})
